function [k_final, ktilde, gamma, ok, report] = synth_k_given_gamma(tau, lambda_n, gamma, lambdas_all)

  [A,B1,B2,C1,C2,D11,D12,D21] = build_generalized_plant(tau, lambda_n, gamma);

  %            exo=[w~;nu~]   u=mu~          z=[x;mu~]; y=theta~
  P = ss(A, [B1 B2], [C1; C2], [D11 D12; D21 0], 1);   % <-- Ts=1 (离散)

  % ===== 2) H∞ 输出反馈： y->u 的补偿器就是 \tilde k(z) =====
  ny = 1; nu = 1;
  opts = hinfsynOptions('Method','ric','Display','off'); % 离散支持
  [ktilde, ~, hinfval] = hinfsyn(P, ny, nu, opts);       % 期望 hinfval < 1
  if hinfval >= 1
    warning('lambda=%.4g, gamma=%.4g infeasible: hinfval=%.4f >= 1.', lambda_n, gamma, hinfval);
  else
    warning('lambda=%.4g, gamma=%.4g feasible: hinfval=%.4f < 1.', lambda_n, gamma, hinfval);
  end

  % ===== 3) 放缩得到最终控制器 k(z) =====
  k_final = sqrt(gamma) * ktilde;

  % ===== 4) (可选) 全模态逐一校验 ||M_i||_inf < 1 =====
  ok = true; report = [];
  if nargin >= 4 && ~isempty(lambdas_all)
    report = verify_all_modes(ktilde, tau, gamma, lambdas_all);
    ok = report.all_modes_ok;
    disp(report);
  end
end

function [A,B1,B2,C1,C2,D11,D12,D21] = build_generalized_plant(tau, lam, gamma)
  % —— 论文 Theorem 2 的闭式系数（标量）——
  p1  = (tau^2*lam^2 + tau*lam*sqrt(4 + tau^2*lam^2))/2;
  p1t = 1 + p1;
  pg  = gamma/p1t^2 + (lam^2)/p1t - gamma;
  p2  = ( pg + sqrt(pg^2 + 4*lam^2*gamma/p1t) )/(2*lam^2);
  p2t = gamma + lam^2*p2;

  fN  = (lam^2*p2/p1t)/p2t;
  fM  = 1/p1t - fN;

  % —— 2x2 子系统矩阵（模态 \widetilde M_i）——
  A  = [1, -fN; 0, fM];
  B2 = [tau*lam; 0];                              % u=mu~
  B1w= [lam/sqrt(p2t); lam/sqrt(p2t)];            % w~ 进入状态
  B1 = [B1w, [0;0]];                              % exo=[w~, nu~]，nu~不进状态

  C2 = [sqrt(gamma), 0];                          % y=theta~
  D21= [0, 1];                                    % nu~ 直接被量测

  % 被控输出 z = [xi; chi; mu~] 以单位权
  C1  = [eye(2); 0 0];                            % 3x2
  D12 = [0; 0; 1];                                % 3x1
  D11 = zeros(3,2);                               % 3x2
end

function report = verify_all_modes(ktilde, tau, gamma, lambdas, tol)
  if nargin < 5 || isempty(tol), tol = 1e-12; end

  n = numel(lambdas);
  vals = nan(n,1);        % 近零 λ 用 NaN 占位
  ok = true;

  for idx = 1:n
    lam = lambdas(idx);
    if abs(lam) <= tol
      % 跳过零/近零特征值（一致体模态）
      continue;
    end

    [A,B1,B2,C1,C2,D11,D12,D21] = build_generalized_plant(tau, lam, gamma);
    P  = ss(A, [B1 B2], [C1; C2], [D11 D12; D21 0], 1);  % Ts=1
    CL = lft(P, ktilde, 1, 1);                           % 关闭 y->u
    Mi = CL(1:3, 1:2);                                   % exo->[z]
    vals(idx) = norm(Mi, inf);

    if isnan(vals(idx))
      continue;  % 跳过占位的 NaN，不做逻辑比较
    end

    if vals(idx) >= 1 - 1e-6
      ok = false;
    end
  end

  report = struct('all_modes_ok', ok, ...
                  'Hinf_each_mode', vals, ...
                  'lambdas', lambdas, ...
                  'skipped_tol', tol);
end
